/**
 * @FileName: CommunicationfeeController.java
 * @Author
 * @Description:
 * @Date 2016年9月19日 下午2:31:22
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.controller.admin;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Activity;
import cn.hpclub.server.model.Tariff;
import cn.hpclub.server.model.TariffClass;
import cn.hpclub.server.model.promotion.Promotion;
import cn.hpclub.server.model.recommend.Recommend;
import cn.hpclub.server.service.ActivityTariffClassRelationService;
import cn.hpclub.server.service.TariffClassRelationService;
import cn.hpclub.server.service.TariffService;
import cn.hpclub.server.service.recommend.RecommendService;
import cn.hpclub.server.util.DateKit;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ObjectUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityController extends BaseAdminController<Activity>{
    private static Logger log = LoggerFactory.getLogger(ActivityController.class);

    public void list(){
        List<Record> list = InterfaceUtil.getAllCity();
        setAttr("city_list", list);// 加载地市列表

        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        int city_id = Integer.parseInt(getPara("city_id", "-1"));

        if(city_id == -1){
            int org_id = InterfaceUtil.getOrgId();
            Record record = InterfaceUtil.getInfoByOrg(org_id);
            if(ObjectUtil.isNotEmpty(record) && ObjectUtil.isNotEmpty(record.getInt("city_id"))){
                city_id = record.getInt("city_id");
            }
        }
        if((!searchInfo.contains("city_id") || "-1".equals(searchInfo.get("city_id"))) && city_id != -1){
            searchInfo.put("city_id", String.valueOf(city_id));
        }
        if("-1".equals(searchInfo.get("city_id"))){
            searchInfo.remove("city_id");
        }
        int city_id_attr = city_id;
        if(StrKit.notBlank(searchInfo.get("city_id"))){
            city_id_attr = Integer.parseInt(searchInfo.get("city_id"));
        }
        setAttr("city_id", city_id_attr);
        findByPageForSearch("SELECT sc.name AS typeName,a.id,a.name,a.type,a.remark,a.sort,a.created_time,a.last_updated_time ",
                ActivityTariffClassRelationService.service.getSqlExceptSelect(searchInfo));
        render("/admin/activity_list.tpl");
    }


    public void validityTypeUnique(){
        JSONObject jo = null;
        String type = getPara("type", "");
        int activityId = getParaToInt("activityId",0);
        boolean flag = ActivityTariffClassRelationService.service.getTariffByCityAndCode(type,activityId);
        if(!flag){
            jo = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "资费代码唯一可用", null);
        }else{
            jo = setResponseObj(ClientApiConstant.ResultCode.FAILED, "资费代码在当前地市已存在", null);
        }
        renderJson(jo.toString());
    }

    public void add(){
        String activity_type_sql = " SELECT st.name as type_name,st.code as type_code," +
                " sv.name,sv.code,sv.value FROM sys_code_value sv LEFT JOIN sys_code_type st ON st.id = sv.type_id " +
                " WHERE st.`code` = 'HDLX' AND st.is_deleted=0 AND sv.is_deleted=0 ";
        List<Record> list = Db.find(activity_type_sql);
        setAttr("activityTypeList", list);
        render("/admin/activity_input.tpl");
    }

    /**
     *
     * @Title: edit
     * @Description:
     */
    public void edit(){
        String id = getPara("id", null);
        if(StrKit.notBlank(id)){
            Activity activity = Activity.dao.findById(id);
            setAttr("activity", activity);
        }
        String activity_type_sql = " SELECT st.name as type_name,st.code as type_code," +
                " sv.name,sv.code,sv.value FROM sys_code_value sv LEFT JOIN sys_code_type st ON st.id = sv.type_id " +
                " WHERE st.`code` = 'HDLX' AND st.is_deleted=0 AND sv.is_deleted=0 ";
        List<Record> list = Db.find(activity_type_sql);
        setAttr("activityTypeList", list);


        render("/admin/activity_input.tpl");
    }


    /**
     *
     * @Title: save
     * @Description:
     */
    public void save(){
        Activity obj = new Activity();
//        String tariffClassIds = getPara("tariff_class_ids", null);
        int activityId = getParaToInt("activityId", 0);

//        if(activityId != 0){// 更新时删除原有的资费大类关系数据，后续重新保存
//            ActivityTariffClassRelationService.service.deleteRelationByActivityId(activityId);
//        }

        String name = getPara("name", null);
        int type = getParaToInt("type", null);
        String sort = getPara("sort", null);
        String remark = getPara("remark", null);
        String title = getPara("title",null);
        String description = getPara("description",null);
        String icon_url = getPara("icon_url",null);
        String  creator = InterfaceUtil.getAdminId() + "";
        int org_id = InterfaceUtil.getOrgId();
        // 获取系统当前时间
        String create_time = DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss");
        // 检查必填字段
        if(StrKit.isBlank(name)
                || StrKit.isBlank(sort) || StrKit.isBlank(creator)
                || StrKit.isBlank(title)|| StrKit.isBlank(description)){
            throw new IllegalArgumentException("参数错误");
        }

        obj.set(Activity.NAME, name);
        obj.set(Activity.TYPE, type);
        obj.set(Activity.REMARK, remark);
        obj.set(Activity.SORT, sort);
        obj.set(Activity.TITLE, title);
        obj.set(Activity.DESCRIPTION, description);
        obj.set(Activity.ICON_URL, icon_url);
        if(activityId != 0){
            // 更新商品信息
            obj.set(Activity.ID, activityId);
            obj.set(Activity.LAST_UPDATED_TIME, new Date());
            obj.set(Activity.LAST_UPDATED_BY, creator);
            obj.update();
        } else{
            obj.set(Activity.CREATED_BY, creator);// 新增时才更新创建人Id
            obj.set(Activity.CREATED_TIME, create_time);
            if(obj.save()){
                activityId = Integer.parseInt(obj.get(Activity.ID).toString());
            }
        }
//        List<Integer> tariffClassIdList = new ArrayList<>();
//        if(tariffClassIds.contains(",")){
//            String[] tariffClassIdArr = tariffClassIds.split(",");
//            for(String tariffClassId : tariffClassIdArr){
//                tariffClassIdList.add(Integer.parseInt(tariffClassId));
//            }
//        } else{
//            tariffClassIdList.add(Integer.parseInt(tariffClassIds));
//        }
//        ActivityTariffClassRelationService.service.saveRelation(activityId, tariffClassIdList);
        redirect("/activity/list");
    }




    /**
     *
     * @Title: deletePromo
     * @Description:通过主键Id删除一条首页弹窗数据
     */
    public void deletePromo(){
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }

        boolean deleted = true;
        for(String id : ids){
            Activity activity = new Activity();
            activity.set(Activity.ID, id);
            activity.set(Activity.IS_DELETED, 1);
            activity.set(Activity.LAST_UPDATED_BY, InterfaceUtil.getAdminId());
            activity.set(Activity.LAST_UPDATED_TIME, DateKit.toStr(new Date(), "yyyy-MM-dd HH:mm:ss"));
            if(!activity.update()){
                deleted = false;
                break;
            }
        }
        Map<String, Object> jsonMap = new HashMap<>();
        jsonMap.put("code", 1000);
        if(deleted){
            jsonMap.put("message", "success");
        } else{
            jsonMap.put("message", "failed");
        }
        renderJson(jsonMap);
    }


}
